********************************************************************************
/*

This file is part of the replication package of "Asset-Price Redistribution" by
Fagereng, Gomez, Gouin-Bonenfant, Holm, Moll, and Natvik. 

This file produces a set of aggregate statistics on housing transaction data
by sector needed to complement the sectoral finacial accounts. 

*/
********************************************************************************

* CONSTRUCT TRANSACTION OVERVIEW ONLY FOR HOUSING WHERE SELLERS = BUYER
u $data/housing_transactions.dta, replace

drop shareSell shareBuy
* generate sum transactions of each type per omsetningsid
bys omsetningsid: egen shareSell = total(share*(seller==1))
bys omsetningsid: egen shareBuy = total(share*(seller==0))
count if shareSell == shareBuy

keep if abs(shareSell-shareBuy) <= 1e-5

replace share = share / shareSell

forval j = 1/5 {
	bys omsetningsid: egen sectorBuy`j' = total(share*(sector==`j')*(seller==0))
	bys omsetningsid: egen sectorSell`j' = total(share*(sector==`j')*(seller==1))
}
bys omsetningsid: keep if _n == 1

forval jj = 1/5 {
	forval jjj = 1/5 {	
		bys year: egen trans_`jj'`jjj' = total(kjopesum*sectorBuy`jj'*sectorSell`jjj')
	}
}

format trans* %20.0g
bys year: keep if _n == 1
keep year trans*


* cpi adjust and convert to dollars
merge m:1 year using $data/cpi_1960_2020_USD.dta, nogen keep(match master) keepusing(cpi)
forval jj = 1/5 {
	forval jjj = 1/5 {	
		replace trans_`jj'`jjj' = trans_`jj'`jjj'/cpi
	}
}

* produce csv file
outsheet year trans* using $output/housing_transactions_by_sector.csv, c replace



********************************************************************************
* CONSTRUCT TRANSACTION OVERVIEW ONLY FOR COOPERATIVES WHERE SELLERS = BUYER
u $data/borett_transactions.dta, replace

drop shareSell shareBuy
* generate sum transactions of each type per omsetningsid
bys omsetningsid: egen shareSell = total(share*(seller==1))
bys omsetningsid: egen shareBuy = total(share*(seller==0))
count if shareSell == shareBuy

keep if abs(shareSell-shareBuy) <= 1e-5

replace share = share / shareSell

forval j = 1/5 {
	bys omsetningsid: egen sectorBuy`j' = total(share*(sector==`j')*(seller==0))
	bys omsetningsid: egen sectorSell`j' = total(share*(sector==`j')*(seller==1))
}
bys omsetningsid: keep if _n == 1

forval jj = 1/5 {
	forval jjj = 1/5 {	
		bys year: egen trans_`jj'`jjj' = total(kjopesum*sectorBuy`jj'*sectorSell`jjj')
	}
}

format trans* %20.0g
bys year: keep if _n == 1
keep year trans*


* cpi adjust and convert to dollars
merge m:1 year using $data/cpi_1960_2020_USD.dta, nogen keep(match master) keepusing(cpi)
forval jj = 1/5 {
	forval jjj = 1/5 {	
		replace trans_`jj'`jjj' = trans_`jj'`jjj'/cpi
	}
}

* produce csv file
outsheet year trans* using $output/cooperative_transactions_by_sector.csv, c replace







